import Vue from 'vue'
import VueRouter from 'vue-router'
import { dynamicsRoutes } from './dynamicsRoutes'
import { staticRoutes } from './staticRoutes'
import eventEmitter from '@/utils/EventEmitter'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: staticRoutes
})

let userPermissions = null // 初始化为 null，表示未获取权限
let isRoutesAdded = false // 标记动态路由是否已添加

const filterRoutesByPermissions = (dyRoutes, permissions) => {
  return dyRoutes.filter(route => {
    return route.requiresRole.some(role => permissions.includes(role))
  })
}

// 监听用户权限更新
eventEmitter.on('userRole', userRole => {
  userPermissions = userRole
  // 权限更新后，动态添加路由
  if (!isRoutesAdded) {
    const finallyRoutes = filterRoutesByPermissions(dynamicsRoutes, userPermissions)
    router.addRoutes(finallyRoutes)
    isRoutesAdded = true
  }
})

router.beforeEach((to, from, next) => {
  // 如果目标路径是 /role，直接放行
  if (to.path === '/role') {
    next()
    return // 终止后续逻辑
  }

  // 如果权限未获取，重定向到 /role
  // if (userPermissions === null) {
  //   next('/role')
  //   return
  // }

  next()
})

export default router
